import { ElMessageBox, MessageBoxState } from 'element-plus';

type ConfirmValue = {
  instance: MessageBoxState;
  done: () => void;
};

/**
 * 确认操作
 * @param message 确认消息内容
 * @param title 标题
 * @returns
 */
export function confirm(callback: () => Promise<any>, message?: string, title?: string): void {
  const finalMessage = message || `此操作不可恢复，是否继续?`;
  const finalTitle = title || `提示`;

  ElMessageBox.confirm(finalMessage, finalTitle, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    buttonSize: 'default',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = '提交中';
        try {
          await callback()
          done();
        } finally {
          instance.confirmButtonLoading = false;
          instance.confirmButtonText = '确认';
          instance.confirmButtonLoading = false;
        }
      } else {
        done();
      }
    }
  });
}
